/*
 *  Copyright 2010-2011 Mark Eschbach
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * $HeadURL: http://phunctional-system-integration.googlecode.com/svn/tags/psi-reactor-2.4/tags/psi-core-2.2.0/src/main/java/com/meschbach/psi/util/FileUploader.java $
 * $Id: FileUploader.java 8 2011-01-31 07:35:05Z meschbach@gmail.com $
 */
package com.meschbach.psi.util;

import com.meschbach.cise.util.StreamCopier;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.fileupload.FileItemStream;

/**
 * A <code>FileUploader</code> mediates the various elements of the Apache Commons
 * File Upload system into a file.
 * <p>
 * NOTE: Internal API - May change at any time for any reason
 *
 * @author "Mark Eschbach" &lt;meschbach@gmail.com&gt;
 * @since 1.1.0
 * @version 1.0.0
 */
public class FileUploader {

    /**
     * The <code>extension</code> should contain the extension desired for the
     * resulting file name.
     */
    protected String extension;
    /**
     * The <code>resultingFile</code> is the file the contents have been written
     * to.  This value is only valid after the
     * <code>upload(String,FileItemStream)</code> has been called.
     */
    protected File resultingFile;

    public FileUploader(String extension) {
        this.extension = extension;
    }

    public File getResultingFile() {
        if (resultingFile == null) {
            throw new IllegalStateException("File must be uploaded proir to inquring about it");
        }
        return resultingFile;
    }

    public void upload(String contextPath, FileItemStream fis) throws IOException {
        /*
         * Create our temporary file
         */
        File temporaryFile = File.createTempFile(contextPath, ".war");
        temporaryFile.deleteOnExit();
        /*
         * Copy the stream into the file
         */
        InputStream fileInputStream = fis.openStream();
        FileOutputStream fos = new FileOutputStream(temporaryFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        new StreamCopier(fileInputStream, bos).doCopy();
        bos.flush();
        bos.close();
        /*
         * Remember our successful result
         */
        resultingFile = temporaryFile;
    }
}
